package com.zhang.gulimall.coupon.service.impl;

import com.zhang.gulimall.coupon.entity.SeckillSkuRelationEntity;
import com.zhang.gulimall.coupon.service.SeckillSkuRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhang.gulimall.common.utils.PageUtils;
import com.zhang.gulimall.common.utils.Query;

import com.zhang.gulimall.coupon.dao.SeckillSessionDao;
import com.zhang.gulimall.coupon.entity.SeckillSessionEntity;
import com.zhang.gulimall.coupon.service.SeckillSessionService;


@Service("seckillSessionService")
public class SeckillSessionServiceImpl extends ServiceImpl<SeckillSessionDao, SeckillSessionEntity> implements SeckillSessionService {

    @Autowired
    SeckillSkuRelationService seckillSkuRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SeckillSessionEntity> page = this.page(
                new Query<SeckillSessionEntity>().getPage(params),
                new QueryWrapper<SeckillSessionEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<SeckillSessionEntity> last3daySession() {
        String start = LocalDateTime.of(LocalDate.now(), LocalTime.MIN).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        String end = LocalDateTime.of(LocalDate.now().plusDays(2), LocalTime.MAX).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        QueryWrapper<SeckillSessionEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().between(SeckillSessionEntity::getStartTime, start, end);
        List<SeckillSessionEntity> list = this.list(queryWrapper);

        List<String> sessionIds = list.stream().map(SeckillSessionEntity::getId).collect(Collectors.toList());
        if (sessionIds.size()>0){
            List<SeckillSkuRelationEntity> skus = seckillSkuRelationService.list(new QueryWrapper<SeckillSkuRelationEntity>().lambda().in(SeckillSkuRelationEntity::getPromotionSessionId, sessionIds));
            for (SeckillSessionEntity entity : list) {
                List<SeckillSkuRelationEntity> collect = skus.stream().filter(s -> entity.getId().equals(s.getPromotionSessionId())).collect(Collectors.toList());
                entity.setSkuRelationEntities(collect);
            }
        }

        return list;
    }
}